import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/utils/_.dart';


/// 单例模式封装 dio
class HttpApi {
  Dio? _dio;
  CancelFunc? _loading;
  late RequestOptions _requestOptions;
  bool isShowLoading = false;
  static HttpApi _instance = HttpApi.instance();
  factory HttpApi() => _instance;

  HttpApi.instance() {
    if (null == _dio) {
      BaseOptions options = new BaseOptions(
        baseUrl: Config.apiUrl['BaseUrl'],
        connectTimeout: 20000,
        contentType: 'application/json; charset=utf-8',
        responseType: ResponseType.json,

      );

      _dio = new Dio(options);
      _dio!.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options,RequestInterceptorHandler handler) {
        if(options.extra['showLoading']){
          _loading =  BotToast.showLoading();
          isShowLoading = true;
        }
         options.headers.putIfAbsent("token", () => SPreferences().getString("token"));
        _requestOptions = options;
        // 请求拦截器
        return handler.next(options);
      }, onResponse: (Response response,ResponseInterceptorHandler  handler)    async {
          if(isShowLoading){
            _loading!();
            isShowLoading = false;
          }
          if(response.requestOptions.extra['isDownLoad']!=null &&response.requestOptions.extra['isDownLoad'])  return handler.next(response);
          switch (response.data["code"]) {
            case 404:
              BotToast.showText(text: response.data["message"]);
              if(response.data['message']=='登录失效'){
                await Tool.deleteUserList(isDeleteLogin: true);
                Modular.to.pushNamedAndRemoveUntil('/signUp', (Route route)=>false);
                return;
              }else{
                return  handler.reject(DioError(requestOptions:_requestOptions,error:response.data["message"],response:response ));
              }
            case 100:
              return handler.next(response);
            default:
              return handler.next(response);
          }
      }, onError: (DioError e,ErrorInterceptorHandler  handler) {
        if(isShowLoading){
          _loading!();
          isShowLoading = false;
        }
        BotToast.showText(text: '请求超时');
        return  handler.reject(e);
      }));
    }
  }

  /// GET 请求
  Future get({required String url,  Options? options, dynamic params}) async {
    Response res = await _dio!.get(url, queryParameters:params , options: options);
    return res.data;
  }

  /// POST 请求
  Future post({required String url, Options? options, dynamic params}) async {
    if(url == 'public/upLoadFile')options!.contentType = 'application/x-www-form-urlencoded';
    Response res = await _dio!.post(url, data: params, options: options);
    return res.data;
  }

  /// 下载文件
  Future downloadFile(String urlPath, String savePath, { required ProgressCallback onReceiveProgress }) async {
    Response response = await _dio!.download(
        urlPath,
        savePath,
        onReceiveProgress: onReceiveProgress,
        options: Options(sendTimeout: 25000, receiveTimeout: 25000,extra: {'showLoading':false,'isDownLoad':true}));
    return response;
  }
}
